package com.ttai.untils;

import android.app.ActivityManager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.ttai.golbal.MyApplication;
import com.ttai.model.dao.DBHelper;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Constant {
    public static final String BASE_URL = "https://www.ttaicloud.com/taisecurity/";
//    public static final String BASE_URL = "https://www.ttaicloud.com/TaiSecurity/";
//    public static final String BASE_URL = "http://192.168.43.200:8080/";
    public static final String GET_ACOUNT_USER = "account/accountUse";
    public static final String APP_NAME = "newTs/appName";
    public static final String TOKEN_LOGIN = "ts/tokenLogin" ;
    public static final String VERIFT_CODE = "ts/sendMessage";
    public static final int VERSION = 6;
    public static final String LOGIN = "ts/login" ;
    public static final String REGISTER = "ts/register" ;
    public static final String LOGOUT = "ts/logout";
    public static final String ACOUNT_DELETE = "account/accountDelete";
    public static final String ACOUNT_ADD = "account/accountAdd";
    public static final String SET_KEY_TIP = "account/setKeyTip";
    public static final String SET_KEY = "account/setKey";
    public static final String ID_DELETE = "newTs/delete";
    public static final String ADD_APP = "newTs/add";
    public static final String OTP = "newTs/otpCreate";
    public static final String STORE_NEWACOUNT = "account/accountList";
    public static final String STORE_TIPACOUNT = "account/searchKeyTip";
    public static final String STORE_IDACOUNT = "newTs/refreashNewTs";
    public static final String IP_ERROR = "newTs/waitLogin";
    public static final String VERIFY_KEY = "account/keyVerify";
    public static final String VERIFY_LOGIN = "ts/securityVerify";
    public static final String VERIFT_MIYAO = "ts/secVerrify";
    public static final String TAI_REGISTER = "newTs/taiRegiser";
    public static final String GET_ACCOUNT = "account/updateKeySearch";
    public static final String NEW_MIYAO = "account/updateKey";


    public static String PATTERN_FULL = "yyyy-MM-dd HH:mm:ss";
    public static String PATTERN_med = "yyyy-MM-dd HH:mm";
    public static String PATTERN_FULL_TRANSNO = "yyyyMMddHHmmss";
    public static String PATTERN_SHORT = "yyyy-MM-dd";
    public static String PATTERN_SHORTSS = "yyyyMMdd";

    /**
     * MD5算法
     * @param scode
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static String mD5Code(String scode) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String result ="";
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update((scode).getBytes("UTF-8"));
        byte b[] = md5.digest();
        int i;
        StringBuffer buf = new StringBuffer("");

        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
            result=buf.toString();
        }
        return result;
    }

    /**
     * 获取手机MAC地址
     */
    public static String getMacAddress(){
        /*获取mac地址有一点需要注意的就是android 6.0版本后，以下注释方法不再适用，不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址，这是googel官方为了加强权限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法来获得mac地址。*/
        //        String macAddress= "";
//        WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        macAddress = wifiInfo.getMacAddress();
//        return macAddress;

        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        return macAddress;
    }

    /**
     * 异或加密算法
     * @param str1
     * @param str2
     * @return
     */

    public static String twoStringXor(String str1, String str2) {
        byte b1[] = str1.getBytes();
        byte b2[] = str2.getBytes();
        byte longbytes[],shortbytes[];
        if(b1.length>=b2.length){
            longbytes = b1;
            shortbytes = b2;
        }else{
            longbytes = b2;
            shortbytes = b1;
        }
        byte xorstr[] = new byte[longbytes.length];

        int i = 0;
        for (; i < shortbytes.length; i++) {
            xorstr[i] = (byte)(shortbytes[i]^longbytes[i]);
        }
        for (;i<longbytes.length;i++){
            xorstr[i] = longbytes[i];
        }
        return new String(xorstr);
    }

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode(String string) {

        StringBuffer unicode = new StringBuffer();

        for (int i = 0; i < string.length(); i++) {

            // 取出每一个字符
            char c = string.charAt(i);

            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }

        return unicode.toString();
    }


    /**
     * unicode 转字符串
     */
    public static String unicode2String(String unicode) {

        StringBuffer string = new StringBuffer();

        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {

            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);

            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }


    public static String shaEncrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-256");// 将此换成SHA-1、SHA-512、SHA-384等参数
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }


    /**
     * 判断程序在前台或者后台
     * @param context
     * @return
     */
    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {

                    return true;
                } else {

                    return false;
                }
            }
        }
        return false;
    }
    // 是否手机号
    public static boolean isMobile(String str) {
        if (StringUtils.isEmpty(str)){
            return false;
        }

        String regex = "(^1\\d{10}$)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 获取当前token值
     */
    public static String getToken(){
        String token = null;
        DBHelper dbHelper = DBHelper.getInstance(MyApplication.getContext());
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor=db.rawQuery("select * from tokenacount",null);
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            token=cursor.getString(cursor.getColumnIndex("token"));
        }
        cursor.close();
        return token;
    }

    /*
     * 将时间戳转换为时间字符串
     */
    public static String timeStampToDateStr(String s, String format)
    {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }


}
